package pw.hais.assistant.service;

import android.accessibilityservice.AccessibilityService;
import android.annotation.TargetApi;
import android.os.Build;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Button;

import pw.hais.utils.L;

/**
 * 软件自动安装
 * Created by hais1992 on 2016/8/24/024.
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class AutoInstallAccessibilityService extends AccessibilityService {
    private AccessibilityNodeInfo nowNodeInfo;

    @Override
    public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
        String pkgName = accessibilityEvent.getPackageName().toString();
        L.e("当前软件包名：" + pkgName);
//        AccessibilityNodeInfo nodeInfo = accessibilityEvent.getSource();
        //nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);

        //下一步
        nowNodeInfo = findViewByTypeAndText(getRootInActiveWindow(), Button.class, "下一步");
        L.e("下一步：---"+nowNodeInfo);
        if (nowNodeInfo != null) nowNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        //下一步
        nowNodeInfo = findViewByTypeAndText(getRootInActiveWindow(),Button.class, "安装");
        L.e("安装：---"+nowNodeInfo);
        if (nowNodeInfo != null) {
            nowNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        }
        //下一步
        nowNodeInfo = findViewByTypeAndText(getRootInActiveWindow(),Button.class, "完成");
        L.e("完成：---"+nowNodeInfo);
        if (nowNodeInfo != null) nowNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
    }

    @Override
    public void onInterrupt() {

    }


    private AccessibilityNodeInfo findViewByText(AccessibilityNodeInfo nodeInfo, String text) {
        return findViewByTypeAndText(nodeInfo, null, text);
    }

    /**
     * 从节点中 根据类型 和 文字 查找控件
     *
     * @param nodeInfo
     * @param clazz
     * @param text
     * @return
     */
    private AccessibilityNodeInfo findViewByTypeAndText(AccessibilityNodeInfo nodeInfo, Class clazz, String text) {
        if (nodeInfo == null) return null;
        for (int i = 0; i < nodeInfo.getChildCount(); i++) {
            AccessibilityNodeInfo node = nodeInfo.getChild(i);
            if (node == null) break;
            else if (node.getChildCount() > 0) findViewByTypeAndText(node, clazz, text);
            else {
                L.e("当前匹配：" + node.getClassName() + "\t\t\t" + node.toString());
//                if (node.toString().contains(text)) {
                if (text.equals(node.getText())) {
                    if (clazz == null) return node;
                    else if (node.getClassName().equals(clazz.getCanonicalName())) {
                        return node;
                    }
                }
            }
        }
        return null;
    }
}
